import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取 .env 文件获取打包路径
function readEnvConfig() {
  const envPath = path.resolve(__dirname, "../.env");
  const envContent = fs.readFileSync(envPath, "utf8");

  const envVars = {};
  envContent.split("\n").forEach((line) => {
    const trimmedLine = line.trim();
    if (trimmedLine && !trimmedLine.startsWith("#")) {
      const [key, ...valueParts] = trimmedLine.split("=");
      if (key && valueParts.length > 0) {
        const value = valueParts.join("=").trim();
        envVars[key.trim()] = value;
      }
    }
  });

  return envVars;
}

// 清空目录内容
function cleanDirectory(dirPath) {
  if (!fs.existsSync(dirPath)) {
    console.log(`📁 目录不存在，创建目录: ${dirPath}`);
    fs.mkdirSync(dirPath, { recursive: true });
    return;
  }

  const items = fs.readdirSync(dirPath);
  for (const item of items) {
    const itemPath = path.join(dirPath, item);
    const stat = fs.statSync(itemPath);

    if (stat.isDirectory()) {
      fs.rmSync(itemPath, { recursive: true, force: true });
      console.log(`🗑️  删除目录: ${item}`);
    } else {
      fs.unlinkSync(itemPath);
      console.log(`🗑️  删除文件: ${item}`);
    }
  }

  console.log(`✅ 目录已清空: ${dirPath}`);
}

// 主函数
function main() {
  try {
    const envVars = readEnvConfig();
    const distPath = envVars.VITE_DIST_PATH || "dist/version";
    const absoluteDistPath = path.resolve(__dirname, "..", distPath);

    console.log(`🧹 开始清空版本目录: ${absoluteDistPath}`);
    cleanDirectory(absoluteDistPath);
    console.log("🎉 清空完成!");
  } catch (error) {
    console.error("❌ 脚本执行失败:", error.message);
    process.exit(1);
  }
}

// 执行主函数
main();
